package com.aso114.project.mvp.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.HistoryAdapter;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.HistoryBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.exam.PracticeReportActivity;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.HelperBean;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 考试成绩
 * Created by asus on 2018/11/8.
 */

public class ExamResultsActivity extends BaseSimpleActivity implements SwipeRefreshLayout.OnRefreshListener, SwipeMenuRecyclerView.LoadMoreListener {
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.layout_title_bar_right_iv)
    ImageView layoutTitleBarRightIv;
    @BindView(R.id.layout_title_bar_right_tv)
    TextView layoutTitleBarRightTv;
    @BindView(R.id.result_left)
    TextView resultLeft;
    @BindView(R.id.result_right)
    TextView resultRight;

    Dialog dialog;
    Intent intent;
    HistoryAdapter historyAdapter;
    HistoryBean qdata;
    @BindView(R.id.result_listView)
    SwipeMenuRecyclerView resultListView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout historyRefreshLy;
    List<HistoryBean.Data> mData = new ArrayList<>();
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.rate)
    TextView rate;
    String cateid = "366";
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;
    private int pageNo = 1;
    //刷新
    private boolean isRefresh = false;

    @Override
    protected int getResouseId() {
        return R.layout.activity_exam_results;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        layoutTitleBarTitleTv.setText("考试成绩");

        LinearLayoutManager layoutManager = new LinearLayoutManager(ExamResultsActivity.this);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置布局管理器
        resultListView.setLayoutManager(layoutManager);
        // 刷新
        historyRefreshLy.setOnRefreshListener(this);
        // 加载
        resultListView.useDefaultLoadMore();
        resultListView.setLoadMoreListener(this);
        isRefresh = true;
        getData(pageNo, cateid);
    }

    @Override
    public void onRefresh() {
        // 刷新
        // 下拉刷新
        pageNo = 1;
        isRefresh = true;
        getData(pageNo, cateid);
    }

    @Override
    public void onLoadMore() {
        // 加载
        // 上拉加载
        pageNo++;
        isRefresh = false;
        getData(pageNo, cateid);
    }

    @Override
    protected void initData() {

//        getData(pageNo,cateid);

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_title_bar_back_iv, R.id.result_left, R.id.result_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;
            case R.id.result_left:
                resultLeft.setTextColor(getResources().getColor(R.color.aff6559));
                resultRight.setTextColor(getResources().getColor(R.color.a333333));
                cateid = Constant.adutst;
                pageNo = 1;
                mData.clear();
                getData(pageNo, cateid);
                break;
            case R.id.result_right:
                resultLeft.setTextColor(getResources().getColor(R.color.a333333));
                resultRight.setTextColor(getResources().getColor(R.color.aff6559));
                pageNo = 1;
                cateid = Constant.essay;
                mData.clear();
                getData(pageNo, cateid);
                break;
        }
    }

    public void getData(final int page, String catid) {

        if (isRefresh) {
            historyRefreshLy.setRefreshing(true);
        }
        CommentModel.getInstant().get_result_list(page, LoginSP.getInstance().getUserAreaId(),
                catid, "1", new CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
//                        dialog.cancel();
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆

                        qdata = (HistoryBean) o;


                        System.out.println("题目总数===" + qdata.getPageinfo().getAnswerCount());

                        if (historyRefreshLy == null) {
                            return;
                        }
                        if (isRefresh) {
                            pageNo = 1;
                            historyRefreshLy.setRefreshing(false);
                            mData.clear();
                        }

                        if (qdata.getPageinfo().getAnswerCount().equals("0")) {
                            number.setText("0");
                            rate.setText("0%");
                        } else {
                            number.setText(qdata.getPageinfo().getAnswerCount());

                            double anscount = Double.valueOf(qdata.getPageinfo().getAnswerCount());
                            double correct = Double.valueOf(qdata.getPageinfo().getCorrectCount());
                            rate.setText(String.format("%2.0f%%", correct / anscount * 100));

                        }

                        if (qdata.getData() == null || qdata.getData().size() == 0) {
                            // 一定要调用这个方法，否则不会触发加载更多。
                            // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
                            // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
//                            historyNullLy.setVisibility(View.VISIBLE);
                            if (page == 1) {
                                historyRefreshLy.setVisibility(View.GONE);
                            } else {
                                resultListView.loadMoreFinish(true, true);
                                ToastUtils.showToast(ExamResultsActivity.this, "已加载全部数据");
                            }
                        } else {
                            historyRefreshLy.setVisibility(View.VISIBLE);
                            mData.addAll(qdata.getData());


                            HistoryAdapter historyAdapter = new HistoryAdapter(ExamResultsActivity.this,
                                    mData, 2);
                            resultListView.setAdapter(historyAdapter);
                            historyAdapter.notifyDataSetChanged();

                            historyAdapter.setOnItemClickListener(new HistoryAdapter.OnItemClickListener() {

                                @Override
                                public void onItemClick(View view, int postion) {
                                    final View dialogview = ExamResultsActivity.this.getLayoutInflater().inflate(R.layout.loading_view, null);
                                    dialog = new Dialog(ExamResultsActivity.this, R.style.dialogStyle);
                                    dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                                            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams
                                            .WRAP_CONTENT));
                                    dialog.getWindow().setGravity(Gravity.CENTER);
                                    // 设置点击外围解散
                                    dialog.setCanceledOnTouchOutside(true);
                                    dialog.setCancelable(true);//设置是否可以按退回键取消
                                    dialog.show();
                                    try {
                                        CommentModel.getInstant().get_history_bank(LoginSP.getInstance().getUserAreaId(), mData
                                                .get(postion).getPaperId(), Constant.adutst, new CallBack() {
                                            @Override
                                            public void onSuccess(Object o, boolean isSuccess, String msg) {
                                                dialog.cancel();
                                                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                                                QuestionBean qdata = (QuestionBean) o;
                                                if (qdata == null) {
                                                    Helper.showToast("获取数据失败，稍后尝试");
                                                    return;
                                                }
                                                System.out.println("题库大小111===" + qdata.getPaperTitle());
                                                System.out.println("题库数组大小===" + qdata.getQuestionBaseList().get(0)
                                                        .getQuestionList().size());
                                                EventBus.getDefault().postSticky(HelperBean.getBaseBean(qdata));
                                                intent = new Intent(ExamResultsActivity.this, PracticeReportActivity.class);
                                                startActivity(intent);
                                            }

                                            @Override
                                            public void onFailure(String fail) {
                                                Helper.showToast("获取题库失败");
                                                dialog.cancel();
                                            }
                                        });
                                    }catch (IndexOutOfBoundsException e){
                                        e.printStackTrace();
                                    }

                                }
                            });

                            resultListView.loadMoreFinish(false, true);
                        }

                    }

                    @Override
                    public void onFailure(String fail) {
                        ToastUtils.showToast(ExamResultsActivity.this, "获取数据失败");
                    }

                });


    }


}
